package com.ruoyi.baseData.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.baseData.domain.dto.MaterialDto;
import com.ruoyi.baseData.domain.vo.MaterialVo;
import com.ruoyi.baseData.service.MaterialService;
import com.ruoyi.common.core.domain.R;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.system.api.domain.SysDictType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    MaterialService materialService;

    @PostMapping("/getMaterialByPage")
    public R export(@RequestBody MaterialDto materialDto)
    {
        return R.ok(materialService.getMaterialByPage(materialDto));
    }

    @PostMapping("/addMaterial")
    public R addTest(@RequestBody MaterialDto materialDto){
        materialService.addMaterial(materialDto);
        return R.ok("添加成功");
    }

    @PostMapping("/delMaterial")
    public R delTest(@RequestBody MaterialDto materialDto){
        materialService.delMaterial(materialDto);
        return R.ok("删除成功");
    }

    @PostMapping("/updateMaterial")
    public R updateTest(@RequestBody MaterialDto materialDto){
        materialService.updateMaterial(materialDto);
        return R.ok("锁定成功");
    }

    @PostMapping("/uploadMaterial")
    public R uploadMaterial(@RequestParam MultipartFile file) throws IOException {
        materialService.uploadMaterial(file);
        return R.ok("锁定成功");
    }


    @PostMapping("/exportMaterial")
    public void exportMaterial(HttpServletResponse response, MaterialDto materialDto) throws IOException {
        Page<MaterialVo> materialVoPage =  materialService.getMaterialByPage(materialDto);
        List<MaterialVo> materialVoList = materialVoPage.getRecords();
//        ExcelUtil<MaterialVo> util = new ExcelUtil<MaterialVo>(MaterialVo.class);
//        util.exportExcel(response, materialVoList, "字典类型");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("Material接口", "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), MaterialVo.class).sheet("sheet1").doWrite(materialVoList);
    }


}
